/***************************

DESCRIPTION: Reshapes wide diagnosis fields to long and renames 
	a few variables

Datasets used:
 (1) `year'\medpar_all_file.dta
 (2) `year'\outpatient_base_claims_j.dta
 (3) `year'\bcarrier_claims_j.dta

Datasets created:
 (1)`year'\medpar_all_file_reshaped.dta
 (2) `year'\outpatient_base_claims_reshaped.dta
 (3) `year'\bcarrier_claims_j_reshaped.dta


***************************/


set more off
capture log close
global path "N:\MedicareClaims-P045601-BE\Work\"
global dpath "N:\MedicareClaims-P045601-BE\Work\ay_data"
global mfixformat "%02.0f"
log using reshape_method, replace

*INPATIENT
foreach year of numlist 2005/2012{
	use "$path\`year'\medpar_all_file.dta", clear 
		foreach k of numlist 1/12 {
			rename DGNS_`k'_CD ICD_DGNS_CD`k'
		}
		rename ADMSN_DT CLM_THRU_DT 
	keep BENE_ID CLM_THRU_DT ICD_DGNS_CD* MEDPAR_ID
	*This is the reshape command
	reshape long ICD_DGNS_CD, i(BENE_ID CLM_THRU_DT MEDPAR_ID) j(diagnosis_number)
		bysort BENE_ID CLM_THRU_DT: gen keep_flag = _n == 1
	replace keep_flag = 1 if !missing(ICD_DGNS_CD) 
	keep if keep_flag
	drop keep_flag
	replace diagnosis = 0 if missing(ICD_DGNS_CD)

	sort BENE_ID CLM_THRU_DT diagnosis
		bysort BENE_ID CLM_THRU_DT: egen diagnosis_count = max(diagnosis)
	
	save "$path\`year'\medpar_all_file_reshaped.dta", replace 
}
 
*OUTPATIENT
foreach year of numlist 2005/2012 {
	use "$path\`year'\outpatient_base_claims_j.dta", clear
	keep BENE_ID CLM_THRU_DT ICD_DGNS_CD*  CLM_ID
	*This is the reshape command
	reshape long ICD_DGNS_CD, i(BENE_ID CLM_THRU_DT CLM_ID) j(diagnosis_number)
		bysort BENE_ID CLM_THRU_DT CLM_ID : gen keep_flag = _n == 1
		 replace keep_flag = 1 if !missing(ICD_DGNS_CD) 
	keep if keep_flag
	drop keep_flag
		 replace diagnosis = 0 if missing(ICD_DGNS_CD)

	sort BENE_ID CLM_THRU_DT CLM_ID  diagnosis
		bysort BENE_ID CLM_THRU_DT CLM_ID : egen diagnosis_count = max(diagnosis)
	
	save "$path\`year'\outpatient_base_claims_reshaped.dta",replace
}

*CARRIER (ambulatory)
foreach year of numlist 2010/2012 {
	use "$path\`year'\bcarrier_claims_j.dta",clear
	keep BENE_ID CLM_THRU_DT ICD_DGNS_CD*  CLM_ID
	*This is the reshape command
	reshape long ICD_DGNS_CD, i(BENE_ID CLM_THRU_DT CLM_ID )  j(diagnosis_number)
		bysort BENE_ID CLM_THRU_DT CLM_ID : gen keep_flag = _n == 1
	 	 replace keep_flag = 1 if !missing(ICD_DGNS_CD) 
	keep if keep_flag
	drop keep_flag
	replace diagnosis = 0 if missing(ICD_DGNS_CD)

	sort BENE_ID CLM_THRU_DT CLM_ID  diagnosis
		bysort BENE_ID CLM_THRU_DT: egen diagnosis_count = max(diagnosis)
	
	save "$path\`year'\bcarrier_claims_j_reshaped.dta",replace
	
}
 

